package io.renren.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.R;
import io.renren.common.utils.RedisUtils;
import io.renren.entity.CommonContentEntity;
import io.renren.service.impl.CommonContentServicelmpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/common/content")
@Api(tags = "固定页面接口")
public class CommonContentController {

    @Autowired
    CommonContentServicelmpl contentServicelmpl;

    @Autowired
    RedisUtils redisUtils;

    @PostMapping("get")
    @ApiOperation("获取内容信息")
    public R get(@RequestBody Map<String, Object> params) {
        try {
            if (params.get("contentKey") == null) {
                return R.error("内容编码不能为空");
            }

            String[] keys = params.get("contentKey").toString().split("[,]");
            List<CommonContentEntity> commonContentEntities = new ArrayList<>();
            if (keys != null) {
                if (keys.length > 10) {
                    return R.error("内容编码不能超过10个");
                }
                for (String key : keys) {
                    CommonContentEntity entity;
                    String value = redisUtils.get("common_content_" + key);
                    if (!StringUtils.isEmpty(value)) {
                        entity = JSON.parseObject(value, CommonContentEntity.class);
                        commonContentEntities.add(entity);
                        continue;
                    }
                    QueryWrapper wrapper = new QueryWrapper<CommonContentEntity>();
                    wrapper.eq("content_key", key);
                    wrapper.eq("enabled", 0);
                    entity = contentServicelmpl.getOne(wrapper);
                    if (entity != null && entity.getId() != null && entity.getId().longValue() > 0) {
                        commonContentEntities.add(entity);
                        redisUtils.set("common_content_" + key, JSON.toJSONString(entity));
                    }
                }
            }

            return R.ok().put("data", commonContentEntities);
        } catch (Exception e) {
            return R.error(9999, "查询内容列表发生异常");
        }
    }


}
